const mongoose = require("mongoose");
const ApiList = require("../models/apilist");
const router = require("koa-router")();
const moment = require("moment");
const { testmongo, gettarget } = require("../db/dbmongo");

router.post("/getapi", async (ctx) => {
  const apilist = await ApiList.find({}, { upass: 0 });
  // apilist.forEach((item) => {
  // 	delete item.upass;
  // });
  ctx.body = apilist;
});

router.post("/deleteapi", async (ctx) => {
  const id = ctx.request.body.id;
  const apilist = await ApiList.deleteOne({ _id: id });
  // apilist.forEach((item) => {
  // 	delete item.upass;
  // });
  ctx.body = apilist;
});

router.post("/addapi", async (ctx) => {
  try {
    const now = moment();
    const payload = {
      apiname: ctx.request.body.apiname,
      sqlname: ctx.request.body.sqlname,
      sqltable: ctx.request.body.sqltable,
      ip: ctx.request.body.ip,
      uname: ctx.request.body.uname,
      upass: ctx.request.body.upass,
      port: ctx.request.body.port,
      urltype: "",
      data: "",
      author: mongoose.mongo.ObjectId(ctx.state.user._id),
      time: now,
    };
    const hadsamename = await ApiList.find({
      apiname: payload.apiname,
    }).countDocuments();
    if (hadsamename != 0) {
      console.log("hadsamename", hadsamename);
      ctx.status = 500;
      ctx.body = { msg: "该接口已被使用" };
      return;
    }

    const url = `mongodb://${payload.uname}:${payload.upass}@${payload.ip}:${payload.port}/${payload.sqlname}`;
    let target;
    try {
      target = await gettarget(url, payload);
    } catch (e) {
      console.log(e);
      target = [];
    }
    payload.data = JSON.stringify(target);
    const state = await ApiList.create({
      _id: mongoose.mongo.ObjectId(),
      ...payload,
    });
    ctx.body = state;
  } catch (e) {
    ctx.status = 500;
    ctx.body = "服务器错误" + e.message;
  }
});
router.post("/editapi", async (ctx) => {
  try {
    const now = moment();
    const payload = {
      apiname: ctx.request.body.apiname,
      sqlname: ctx.request.body.sqlname,
      sqltable: ctx.request.body.sqltable,
      ip: ctx.request.body.ip,
      uname: ctx.request.body.uname,
      upass: ctx.request.body.upass,
      port: ctx.request.body.port,
      urltype: "",
      data: "",
      author: mongoose.mongo.ObjectId(ctx.state.user._id),
      time: now,
    };
    const url = `mongodb://${payload.uname}:${payload.upass}@${payload.ip}:${payload.port}/${payload.sqlname}`;
    let target;
    try {
      target = await gettarget(url, payload);
    } catch (e) {
      console.log(e);
      target = [];
    }
    payload.data = JSON.stringify(target);
    const state = await ApiList.updateOne(
      {
        apiname: payload.apiname,
      },
      { $set: { ...payload } },
      {
        runValidators: true,
        multi: true,
      }
    );
    ctx.body = state;
  } catch (e) {
    ctx.status = 500;
    ctx.body = "服务器错误" + e.message;
  }
});

router.post("/useapi", async (ctx) => {
  try {
    const _id = ctx.request.body.id;
    const payload = await ApiList.findOne({ _id });
    if (!payload) {
      ctx.status = 500;
      ctx.body = { msg: "该接口没有查到数据" };
      return;
    }
    const url = `mongodb://${payload.uname}:${payload.upass}@${payload.ip}:${payload.port}/${payload.sqlname}`;
    let target;
    try {
      target = await gettarget(url, payload);
    } catch (e) {
      console.log(e);
      target = [];
    }
    const data = JSON.stringify(target);
    ctx.body = data;
  } catch (e) {
    ctx.status = 500;
    ctx.body = "服务器错误" + e.message;
  }
});

router.post("/testconnect", async (ctx) => {
  try {
    const now = moment();
    const payload = {
      apiname: ctx.request.body.apiname,
      sqlname: ctx.request.body.sqlname,
      sqltable: ctx.request.body.sqltable,
      ip: ctx.request.body.ip,
      uname: ctx.request.body.uname,
      upass: ctx.request.body.upass,
      port: ctx.request.body.port,
      urltype: "",
      data: "",
      time: now,
    };
    const url = `mongodb://${payload.uname}:${payload.upass}@${payload.ip}:${payload.port}/${payload.sqlname}`;
    let res;
    try {
      res = await testmongo(url, payload);
    } catch (e) {
      res = "数据库连接错误：无效的地址";
    }
    ctx.body = res;
  } catch (e) {
    ctx.status = 500;
    ctx.body = "服务器错误" + e.message;
  }
});

router.post("/test", async (ctx) => {
  ctx.body = "123";
});

// router.post("/setgroup", async (ctx) => {
// 	const _id = mongoose.mongo.ObjectId(ctx.request.body.gid);
// 	const name = ctx.request.body.name;
// 	console.log(_id, name);
// 	try {
// 		const state = await GroupList.updateOne(
// 			{ _id: _id },
// 			{ $set: { name } },
// 			{
// 				runValidators: true,
// 			}
// 		);
// 		ctx.body = {
// 			msg: state,
// 		};
// 	} catch (e) {
// 		console.log(e);
// 		ctx.body = {
// 			msg: "更新失败",
// 		};
// 	}
// });

// router.post("/deletegroup", async (ctx) => {
// 	try {
// 		const _id = ctx.request.body.gid;
// 		console.log(_id);
// 		const update = await Project.updateMany(
// 			{ groupID: _id },
// 			{ $set: { groupID: "-1" } },
// 			{
// 				runValidators: true,
// 				multi: true,
// 			}
// 		);
// 		console.log(update);
// 		const state = await GroupList.deleteOne({ _id });
// 		ctx.body = {
// 			msg: "删除成功",
// 			body: {
// 				update: update,
// 				state: state,
// 			},
// 		};
// 	} catch (e) {
// 		console.log(e);
// 		ctx.body = {
// 			msg: "删除失败",
// 		};
// 	}
// });

module.exports = router;
